package cn.edu.xmu.restfuldemo.dao;

import cn.edu.xmu.restfuldemo.mapper.OrdersMapper;
import cn.edu.xmu.restfuldemo.model.*;
import cn.edu.xmu.restfuldemo.util.ReturnObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;


@Repository
public class OrdersDao {
    private Logger logger = LoggerFactory.getLogger(OrdersDao.class);

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 创建Goods对象
     * @param orders 传入的orders对象
     *rdeturn 返回对象ReturnObj
     */
    public ReturnObject<Orders> createOrders(Orders orders){
//        GoodsPo goodsPo = goods.gotGoodsPo();
//        String seqNum = genSeqNum();
//        goodsPo.setGoodsSn("G"+seqNum);
        OrdersPo ordersPo = orders.gotOrdersPo();

        int ret = ordersMapper.createOrders(ordersPo);
        if (orders.getOrderItems() != null) {
            for (OrderItem orderItem : orders.getOrderItems()) {
                OrderItemPo orderItemPo = orderItem.getOrderItemPo();
                orderItemPo.setOrderId(ordersPo.getId());
                ret = ordersMapper.createOrders(ordersPo);
            }
        }
        ReturnObject<Orders> returnObject = new ReturnObject<>(orders);
        return returnObject;
    }
    /**
     * 用OrdersPo对象找Orders对象
     * @param ordersPo 条件对象，所有条件为AND，仅有索引的值可以作为条件
     * @param withOrderItem 是否带关联的Product（有性能问题，不要一次返回太多Goods对象）
     * @return  Goods对象列表，带关联的Product返回
     */
    public ReturnObject<List<Orders>> findOrders(OrdersPo ordersPo, Boolean withOrderItem){
        logger.info("findOrders: ordersPo =" + ordersPo+" withProduct = "+withOrderItem);
        List<OrdersPo> ordersPos = ordersMapper.findOrders(ordersPo);
        logger.info("findOrders: ordersPos =" + ordersPos);
        List<Orders> retOrders = new ArrayList<>(ordersPos.size());
        OrderItemPo orderItemPo =  null;

        if (withOrderItem) {
            orderItemPo = new OrderItemPo();
        }

        for (OrdersPo ordersItem : ordersPos){
            Orders item = new Orders(ordersItem);
            if (withOrderItem) {
                orderItemPo.setOrderId(ordersItem.getId());
                List<OrderItemPo> orderItemPos = ordersMapper.findOrderItemPo(orderItemPo);
                List<OrderItem> orderItemList = new ArrayList<>(orderItemPos.size());
                for (OrderItemPo orderItemPo1: orderItemPos) {
                    OrderItem orderItem = new OrderItem(orderItemPo1);
                    orderItemList.add(orderItem);
                }
                item.setOrderItemList(orderItemList);
            }
            retOrders.add(item);
        }
        logger.info("findGoods: retOrders = "+retOrders +", withOrderItem ="+withOrderItem);
        return new ReturnObject<>(retOrders);
    }

}
